package cn.comtom.ewbs.signature.common.config;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import cn.hutool.core.date.DatePattern;

/**
 * 属性编辑器
 * @author liuhy
 *
 */
@ControllerAdvice
public class GlobalControllerAdiviceController {
	
    /**
     * 注册属性编辑器
     * @param binder 编辑器
     */
    @InitBinder
    public void dataBind(WebDataBinder binder) {
        ///java.lang.String格式化
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        //java.util.Date类型格式化
        SimpleDateFormat dateFormat = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
        //java.time.LocalDateTime类型格式化
        binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                if (!StringUtils.isEmpty(text)) {
                    setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN)));
                }
            }
        });
    }
}
